<template>
  <div class="edit-page-wrap">
    <Head title="台区信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="90px"
          class="edit-form-wrap"
        >
          <el-form-item label="台区名称" prop="platformAreaName">
            <el-input
              v-model.trim="ruleForm.platformAreaName"
              placeholder="请输入台区名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="台区编码"
            prop="platformAreaCode"
            class="has-tips"
          >
            <el-input
              v-model.trim="ruleForm.platformAreaCode"
              placeholder="请输入台区编码"
              maxlength="30"
              clearable
            />
            <div class="tip">
              <div class="icon"></div>
              台区编码需保证唯一，仅支持输入字母或数字
            </div>
          </el-form-item>
          <el-form-item label="关联电桩" prop="equipmentIds" class="has-tips">
            <QcTree
              ref="treeEquipmentRef"
              :setCheckedKeys="ruleForm.equipmentIds"
              :data="optionsS.equipmentTreeData"
              :showCheckbox="true"
              @handleCheck="handleEquipment"
            ></QcTree>
            <div class="tip">
              <div class="icon"></div>
              操作说明：请勿将同一电桩绑定多个台区，若所选电桩已被其他台区绑定，本次操作会直接解绑旧台区
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import { equipmentTreeDataNoPriceSet } from '@/service/apis/org';
import {
  getPlatformAreaById,
  savePlatformArea,
  updatePlatformArea,
  checkIsExistsCodeByChanelId,
} from '@/service/apis/pile';
import { IS_EN_NUMBER } from '@/utils/verify';

import { FormInstance, FormRules } from 'element-plus';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();

const optionsS = reactive({
  equipmentTreeData: [] as any,
});

const ruleForm: any = reactive({
  id: '',
  platformAreaName: '', // 台区名称
  platformAreaCode: '', // 台区编码
  equipmentIds: [] as any,
});

const checkCode = (rule: any, value: any, callback: any) => {
  checkIsExistsCodeByChanelId({
    platformAreaCode: ruleForm.platformAreaCode,
    id,
  }).then((res: any) => {
    console.log(res);
    if (res == '0') {
      callback(new Error('台区编码不能重复'));
    } else {
      callback();
    }
  });
};

const rules = reactive<FormRules>({
  platformAreaName: [
    { required: true, message: '请输入台区名称', trigger: 'blur' },
  ],
  platformAreaCode: [
    { required: true, message: '请输入台区编码', trigger: 'blur' },
    {
      pattern: IS_EN_NUMBER,
      message: '请输入正确的台区编码，仅支持输入字母或数字',
      trigger: 'blur',
    },
    { validator: checkCode, trigger: ['blur'] },
  ],
  equipmentIds: [
    { required: true, message: '请选择关联电桩', trigger: ['blur', 'change'] },
  ],
});

equipmentTreeDataNoPriceSet({}).then((res: any) => {
  if (res) {
    optionsS.equipmentTreeData = [...res];
  }
});

if (id) {
  getPlatformAreaById({ id }).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
    }
  });
}

const back = () => {
  router.go(-1);
};

const handleEquipment = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.equipmentIds = checkedChildData;
  ruleFormRef.value?.validateField('equipmentIds');
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  console.log(ruleForm);
  if (id) {
    updatePlatformArea(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    savePlatformArea(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>
